/**
 * Copyright  2025, Hai Yue Xing He  ZHAO LIMIN
 *
 * @author        ZHAO LIMIN
 * @version       1.0.1
 * @since         2025-04
 * RuntimeError.ts    矩形类
 * 构建一个异常对象，该对象由于运行时可能发生的错误而被抛出，例如：
 * 内存不足，无法编译着色器等。如果函数可能会抛出此异常
 * 例外情况下，调用代码应准备好捕获它。
 * <br /><br />
 * 另一方面，a {@link DeveloperError}表示由于以下原因导致异常
 * 到开发人员错误，例如，无效参数，这通常表明在
 * 呼叫码。
 */
import { defined } from './Defined'
import { defaultValue } from './HYXHDefaultValue'
export class HRuntimeError extends Error {
  /**
   *
   * @alias RuntimeError
   * @constructor
   * @extends Error
   *
   * @param {string} [message] The error message for this exception.
   *
   * @see RuntimeError
   */
  constructor(message: string) {
    super(message)
    this.name = 'RuntimeError'
    /**
     * The explanation for why this exception was thrown.
     * @type {string}
     * @readonly
     */
    this.message = message
    let stack
    try {
      throw new Error()
    } catch (error) {
      if (error instanceof HRuntimeError) {
        console.error('捕获到自定义错误:', error.message)
      } else {
        console.error('发生错误:', error)
      }
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const err = error
      if (defined(err.stack)) {
        stack = err.stack
      }
    }
    this.stack = stack
  }

  /**
   * @private
   */
  private static throwInstantiationError(): HRuntimeError {
    throw new HRuntimeError('This function defines an interface and should not be called directly.')
  }

  public toString(): string {
    let str = `${this.name}: ${this.message}`
    let _stack_name = ''
    if (defined(this.stack)) {
      _stack_name = defaultValue<string>(this.stack?.toString(), '')
    }
    if (defined(this.stack)) {
      str += `\n${_stack_name}`
    }
    return str
  }
}

